define(function (require, exports) {
    var initUrl = function (action, param) {
        return ctx + "/api/ui/" + action + (param ? "?" + param : "");
    };

    var getFilter = function (filterRegion, filterParam) {
        var param = "";

        if (filterRegion) {
            if (!(filterRegion instanceof jQuery)) {
                filterRegion = $(filterRegion);
            }

            filterRegion.find("[name^='q_']").each(function () {
                var key = $(this).attr("name");
                var value = $(this).val();

                param = param + "&" + encodeURIComponent(key) + "=" + encodeURIComponent(value);

            });
        }

        if (filterParam) {
            for (var key in filterParam) {
                param = param + "&" + encodeURIComponent(key) + "=" + encodeURIComponent(filterParam[key]);
            }
        }

        return param;
    };

    /**
     * 初始化api参数
     */
    var initApiOptions = function (apiOptions) {
        var param = "";

        for (var key in apiOptions) {
            var value = apiOptions[key];

            //如果是函数，则跳过
            if (key == "filledBy" || typeof (value) == "function") {
                continue;
            }

            // 处理过滤条件区域
            if (key == "filterRegion") {
                param += getFilter(value);
                continue;
            }

            // 处理额外过滤条件
            if (key == "filter") {
                param += getFilter(null, value);
                continue;
            }

            if (key == "param") {
                value = $.toJSON(value);
            }

            param = param + "&" + encodeURIComponent(key) + "=" + encodeURIComponent(value);
        }

        return param;
    };

    exports.filter = function (target, action, filter, apiOptions) {
        if (!(target instanceof jQuery)) {
            target = $(target);
        }

        var apiOptionsBackup = target.data("apiOptions");

        if (apiOptions) {
            for (var key in apiOptions) {
                apiOptionsBackup[key] = apiOptions[key];
            }
        }

        target.data("apiOptions", apiOptionsBackup);
        filter(initUrl(action, initApiOptions(apiOptionsBackup)));
    };

    exports.initUrl = initUrl;
    exports.initApiOptions = initApiOptions;

    exports.jq = function (target, required) {
        if (typeof required == "undefined") {
            required = true;
        }

        if (!target) {
            alert("没有指定元素");
            return null;
        }

        if (!(target instanceof jQuery)) {
            target = $(target);
        }

        if (target.length == 0 && required) {
            alert(target.selector + "无法找到指定元素");
            return null;
        }

        return target;
    };
});